package com.jxauaia.contest.controller;

import com.jxauaia.contest.common.response.Result;
import com.jxauaia.contest.model.dto.ChangePasswordDTO;
import com.jxauaia.contest.model.dto.UserProfileDTO;
import com.jxauaia.contest.model.entity.User;
import com.jxauaia.contest.service.FileService;
import com.jxauaia.contest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    private final FileService fileService;

    @Autowired
    public UserController(UserService userService, FileService fileService) {
        this.userService = userService;
        this.fileService = fileService;
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/profile")
    public Result<User> getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.findByUsername(username);
        
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        
        // 不返回敏感信息
        user.setPassword(null);
        return Result.success(user);
    }

    /**
     * 更新用户资料
     */
    @PutMapping("/profile")
    public Result<User> updateProfile(@RequestBody @Validated UserProfileDTO userProfileDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);
        
        if (currentUser == null) {
            return Result.error(404, "用户不存在");
        }
        
        User updatedUser = userService.updateUserProfile(currentUser.getId(), userProfileDTO);
        return Result.success("个人信息更新成功", updatedUser);
    }

    /**
     * 上传头像
     */
    @PostMapping("/avatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.findByUsername(username);
            
            if (currentUser == null) {
                return Result.error(404, "用户不存在");
            }
            
            // 上传头像文件
            String avatarUrl = fileService.uploadFile(file, "avatars");
            
            // 更新用户头像
            UserProfileDTO userProfileDTO = new UserProfileDTO();
            userProfileDTO.setAvatar(avatarUrl);
            userService.updateUserProfile(currentUser.getId(), userProfileDTO);
            
            return Result.success("头像上传成功", avatarUrl);
        } catch (IOException e) {
            return Result.error(500, "头像上传失败: " + e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    public Result<Boolean> changePassword(@RequestBody @Validated ChangePasswordDTO changePasswordDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);
        
        if (currentUser == null) {
            return Result.error(404, "用户不存在");
        }
        
        boolean success = userService.changePassword(currentUser.getId(), changePasswordDTO);
        return success ? Result.success("密码修改成功", true) : Result.error(400, "密码修改失败");
    }

    /**
     * 注销账号
     */
    @PostMapping("/deactivate")
    public Result<Boolean> deactivateAccount() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);
        
        if (currentUser == null) {
            return Result.error(400, "用户未登录");
        }
        
        boolean success = userService.deactivateAccount(currentUser.getId(), currentUser.getId());
        return success ? Result.success("账号已注销", true) : Result.error(400, "注销失败");
    }
}
